/**
 * Copyright (c) 2018 开源 All rights reserved.
 * <p>
 * https://www.chengcang.com
 * <p>
 * 版权所有，侵权必究！
 */

package com.chengcang.admin.modules.security.oauth2;

import com.chengcang.admin.modules.security.entity.SysUserTokenEntity;
import com.chengcang.admin.modules.security.service.ShiroService;
import com.chengcang.admin.modules.security.user.SecurityUser;
import com.chengcang.admin.modules.security.user.UserDetail;
import com.chengcang.admin.modules.sys.entity.SysUserEntity;
import com.chengcang.admin.modules.sys.entity.UserTenant;
import com.chengcang.common.constant.RedisConstant;
import com.chengcang.common.constant.TokenExpireConstant;
import com.chengcang.common.enums.UserTenantStatusEnum;
import com.chengcang.common.exception.ErrorCode;
import com.chengcang.common.redis.RedisUtils;
import com.chengcang.common.utils.ConvertUtils;
import com.chengcang.common.utils.MessageUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 认证
 *
 * @author zhanli
 */
@Component
public class Oauth2Realm extends AuthorizingRealm {
    @Autowired
    private ShiroService shiroService;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof Oauth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserDetail user = (UserDetail) principals.getPrimaryPrincipal();

        //用户权限列表
        Set<String> permsSet = shiroService.getUserPermissions(user);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();
        Object userDetailObj = redisUtils.get(accessToken);

        UserDetail userDetail;
        if (Objects.isNull(userDetailObj)) {
            //根据accessToken，查询用户信息
            SysUserTokenEntity tokenEntity = shiroService.getByToken(accessToken);
            //token失效
            if (tokenEntity == null || tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) {
                throw new IncorrectCredentialsException(MessageUtils.getMessage(ErrorCode.TOKEN_INVALID));
            }
            //查询用户信息
            SysUserEntity userEntity = shiroService.getUser(tokenEntity.getUserId());
            // 查询租户信息
            //转换成UserDetail对象
            userDetail = ConvertUtils.sourceToTarget(userEntity, UserDetail.class);
            //获取用户对应的部门数据权限
            List<Long> deptIdList = shiroService.getDataScopeList(userDetail.getId());
            userDetail.setDeptIdList(deptIdList);
            // 获取租户信息
            List<UserTenant> userTenantList = shiroService.getUserTenantList(userDetail.getId());
            userDetail.setTenantList(userTenantList);
            if (CollectionUtils.isNotEmpty(userTenantList)) {
                Map<Long, Integer> statusMap = userTenantList.stream().collect(Collectors.toMap(UserTenant::getTenantId, UserTenant::getStatus));
                Integer defaultTenantStatus = statusMap.get(userDetail.getDefaultTenantId());
                if (defaultTenantStatus == UserTenantStatusEnum.DISABLE.value()) {
                    throw new LockedAccountException(MessageUtils.getMessage(ErrorCode.TENANT_LOCK));
                }
            }
            //账号锁定
            if (userDetail.getStatus() == UserTenantStatusEnum.DISABLE.value()) {
                throw new LockedAccountException(MessageUtils.getMessage(ErrorCode.ACCOUNT_LOCK));
            }
            redisUtils.set(accessToken, userDetail, TokenExpireConstant.EXPIRE);
            Optional.ofNullable(tokenEntity.getTenantId()).ifPresent(o -> {
                String userKey = RedisConstant.SYS_USER + SecurityUser.getUserId();
                long expireMillisSecond = tokenEntity.getExpireDate().getTime() - System.currentTimeMillis();
                redisUtils.set(userKey, tokenEntity.getTenantId(), expireMillisSecond / 1000);
            });
        } else {
            userDetail = (UserDetail) userDetailObj;
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userDetail, accessToken, getName());
        return info;
    }

}